jQuery(document).ready(function() {
    /*登录表单验证*/
    $("#loginForm").bootstrapValidator({
        message: 'This value is not valid',
        excluded: [':disabled'], //[':disabled', ':hidden', ':not(:visible)'] //设置隐藏组件可验证
        feedbackIcons: {
            validating: 'glyphicon glyphicon-refresh'
        },
        fields: {
            name: {
                trigger: "change", //针对赋值的文本框执行change事件
                validators: {
                    notEmpty: {
                        message: '请输入用户名'
                    }
                }
            },
            pwd: {
                validators: {
                    notEmpty: {
                        message: '请输入密码'
                    },
                    regexp: { //同时验证手机号和固话
                        regexp: /^([0-9]|[a-zA-Z]){6,16}$/,
                        message: '密码为6-16位字母或数字'
                    }
                }
            },
            Txtidcode: {
                trigger: "change", //针对赋值的文本框执行change事件
                validators: {
                    notEmpty: {
                        message: '请输入验证码'
                    },
                    callback: {
                        message: '验证码不正确',
                        callback: function(value, validator, $field) { //
                            if (value == "" || value == null) {
                                /*alert(123);*/
                                return true;
                            }
                            var IsBy = $.idcode.validateCode();
                            if (IsBy) {
                                return true;
                            } else {
                                return false;
                            }
                        }
                    }
                }
            }
        }
    });

    /*注册表单验证*/
    $("#registerForm").bootstrapValidator({
        message: 'This value is not valid',
        excluded: [':disabled', ':hidden', ':not(:visible)'], //设置隐藏组件可验证
        feedbackIcons: {
            validating: 'glyphicon glyphicon-refresh'
        },
        fields: {
            name: {
                validators: {
                    notEmpty: {
                        message: '请输入用户名'
                    },
                    regexp: {
                        regexp: /^[\w\u4e00-\u9fa5]{2,6}$/,
                        message: '用户名为2-6位中文、字母、数字或下划线组合'
                    }
                }
            },
          /*  sex: {
                trigger: "change", //针对赋值的文本框执行change事件
                validators: {
                    notEmpty: {
                        message: '请选择性别'
                    }
                }
            },*/
            /*organization:{
                trigger: "change", //针对赋值的文本框执行change事件
                validators: {
                    notEmpty: {
                        message: '请选择所属机构'
                    }
                }
            },*/
            userAccount:{
                validators: {
                    notEmpty: {
                        message: '请输入账号'
                    },
                    regexp: {
                        regexp: /(^1[34578]\d{9}$)|(^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$)/,
                        message: '手机号或邮箱格式不正确'
                    }
                }
            },
            identifyingCode:{
                validators: {
                    notEmpty: {
                        message: '请输入验证码'
                    },
                    callback: {
                        message: '验证码为6位数字',
                        callback: function (value, validator, $field) { //
                            if(value==""){
                                return true;
                            }else{
                                var reg= /^\d{6}$/;
                                if(reg.test(value)){
                                    return true;
                                }else{
                                    return false;
                                }
                            }
                        }
                    }
                }
            },
            pwd: {
                validators: {
                    notEmpty: {
                        message: '请输入密码'
                    },
                    regexp: {
                        regexp: /^([0-9]|[a-zA-Z]){6,16}$/,
                        message: '密码为6-16位字母或数字'
                    },
                    identical: {
                        field: 'pwd1',
                        message: '两次输入的密码不相符'
                    }
                }
            },
            pwd1: {
                validators: {
                    notEmpty: {
                        message: '请输入确认密码'
                    },
                    regexp: { //同时验证手机号和固话
                        regexp: /^([0-9]|[a-zA-Z]){6,16}$/,
                        message: '密码为6-16位字母或数字'
                    },
                    identical: {
                        field: 'pwd',
                        message: '两次输入的密码不相符'
                    }
                }
            }
        }
    });

    /*找回密码表单验证*/
    $("#revertPwdForm").bootstrapValidator({
        message: 'This value is not valid',
        excluded: [':disabled'], //[':disabled', ':hidden', ':not(:visible)'] //设置隐藏组件可验证
        feedbackIcons: {
            validating: 'glyphicon glyphicon-refresh'
        },
        fields: {
            userAccount:{
                trigger: "change", //针对赋值的文本框执行change事件
                validators: {
                    notEmpty: {
                        message: '请输入手机号或邮箱'
                    },
                    regexp: {
                        regexp: /(^1[34578]\d{9}$)|(^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$)/,
                        message: '手机号或邮箱格式不正确'
                    }
                }
            },
            identifyingCode:{
                trigger: "change", //针对赋值的文本框执行change事件
                validators: {
                    notEmpty: {
                        message: '请输入验证码'
                    },
                    callback: {
                        message: '验证码为6位数字',
                        callback: function (value, validator, $field) { //
                            var reg= /^\d{6}$/;
                            if(reg.test(value)){
                                return true;
                            }else{
                                return false;
                            }
                        }
                    }
                }
            }
        }
    });

    /*找回密码内两遍新密码验证*/
    $("#newPwdForm").bootstrapValidator({
        message: 'This value is not valid',
        excluded: [':disabled'], //[':disabled', ':hidden', ':not(:visible)'] //设置隐藏组件可验证
        feedbackIcons: {
            validating: 'glyphicon glyphicon-refresh'
        },
        fields: {
            pwd: {
                validators: {
                    notEmpty: {
                        message: '请输入密码'
                    },
                    regexp: {
                        regexp: /^([0-9]|[a-zA-Z]){6,16}$/,
                        message: '密码为6-16位字母或数字'
                    },
                    identical: {
                        field: 'pwd1',
                        message: '两次输入的密码不相符'
                    }
                }
            },
            pwd1: {
                validators: {
                    notEmpty: {
                        message: '请输入确认密码'
                    },
                    regexp: { //同时验证手机号和固话
                        regexp: /^([0-9]|[a-zA-Z]){6,16}$/,
                        message: '密码为6-16位字母或数字'
                    },
                    identical: {
                        field: 'pwd',
                        message: '两次输入的密码不相符'
                    }
                }
            }
        }
    });

    /*加载组织机构树结构*/
    $.fn.zTree.init($("#treeDemo"), setting);

});

function swapScreen(id) {
    jQuery('.visible').removeClass('visible animated fadeInUp');
    jQuery('#' + id).addClass('visible animated fadeInUp');
}

/*图形验证码初始化*/
$.idcode.setCode();

/*登录按钮点击事件*/
function gotoLogin() {
    var $formlist = $('#loginForm');
    var data = $formlist.data('bootstrapValidator');
    if (data) {
        // 修复记忆的组件不验证
        data.validate();
        if (!data.isValid()) {
            return false;
        }
    }

    /*表单提交方法*/
    var name = $("#loginForm input[name='name']").val();
    var pwd = $("#loginForm input[name='pwd']").val();
    /*判断登录账号是手机号或邮箱号*/
    var regPhone = /^1[34578]\d{9}$/;/*验证手机*/
    var regEmail = /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;/*验证邮箱*/
    if(regPhone.test(name)){
        var loginFormDate = {"phone":name,"pwd":pwd};  //账号为手机时传递参数
    }else if(regEmail.test(name)){
        var loginFormDate = {"email":name,"pwd":pwd};  //账号为邮箱时传递参数
    }else if(name=="admin"){
        var loginFormDate = {"phone":name,"pwd":pwd};  //账号为手机时传递参数
    }
    $.ajax({
        url:"../session/login",
        data:loginFormDate,
        type:"post",
        dataType:"json",
        success:function(data){
            if (data.code==0){
                window.location.href = "../session/toIndex";
            }else{
                layer.alert(data.msg, {icon: 2});
            }
        }
    });
}

/*回车事件监听执行登录方法*/
$("body").keydown(function() {
    if (event.keyCode == "13") {//keyCode=13是回车键
        gotoLogin();
    }
});


// 找回密码弹出框内按步骤操作js控制
$(function() {
    var codeData="";
    //下一步按钮点击事件
    $("#btn_part1").click(function() {
        /*注册表单验证*/
        var $formlist = $('#revertPwdForm');
        var data = $formlist.data('bootstrapValidator');
        if (data) {
            // 修复记忆的组件不验证
            data.validate();
            if (!data.isValid()) {
                return false;
            }
        }
        var forgetData = {};
        var userAccount = $("#revertPwdForm input[name='userAccount']").val();
        var myreg = /^1[34578]\d{9}$/;/*验证手机*/
        var myreg1 = /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;/*验证邮箱*/
        if(myreg.test(userAccount)){
            forgetData.phone = userAccount;
        }else if(myreg1.test(userAccount)){
            forgetData.email = userAccount;
        }
        forgetData.verificationCode =  $("#revertPwdForm input[name='identifyingCode']").val();
        $.ajax({
            async : false,
            type : 'POST',
            url : "../session/getVerificationCodeTorFas",// 请求的action路径
            data:forgetData,
            dataType:'json',
            success : function(data){
                if(data.code==0){
                    $(".part1").hide();
                    $(".part2").show();
                    $(".step li").eq(1).addClass("on");
                    $("#revertPwdForm").find(":input").not(":button").val("");
                    $('#revertPwdForm').bootstrapValidator('resetForm');
                    codeData = data.res;
                }else{
                    layer.msg(data.msg);
                }
            }
        })

       /* */
    });
    //重置按钮点击事件
    $("#btn_part2").click(function() {
        /*注册表单验证*/
        var $formlist = $('#newPwdForm');
        var data = $formlist.data('bootstrapValidator');
        if (data) {
            // 修复记忆的组件不验证
            data.validate();
            if (!data.isValid()) {
                return false;
            }
        }
        var newPwdData = {};      //构造参数
        newPwdData.id =codeData.id;
        newPwdData.name = codeData.name;
        newPwdData.sex = codeData.sex;
        newPwdData.phone = codeData.phone;
        newPwdData.email = codeData.email;
        newPwdData.organizationId = codeData.organizationId;
        newPwdData.type = codeData.type;
        newPwdData.pwd = $("#newPwdForm input[name='pwd1']").val();
        $.ajax({
            url:"../session/register",
            data:newPwdData,
            type:"post",
            dataType:"json",
            success:function(data){
                if (data.code==0){
                    layer.msg(data.msg);
                    $(".part2").hide();
                    $(".part1").show();
                    $(".step li").eq(2).addClass("on");
                    $("#revertPwdForm").find(":input").not(":button").val("");
                    $('#revertPwdForm').bootstrapValidator('resetForm');//重置表单是重置表单验证
                    swapScreen('login');return false;
                }else{
                    layer.msg(data.msg);
                }
            }
        })
    });


    /*****************注册及找回密码发送验证码代码********************/
    var register = "zc";
    var forgetPwd = "zhmm";
    $("#getCode").click(function(){   //注册
        var phonenum = $("#registerForm input[name='userAccount']").val();
        sendMessage(register,phonenum);
    })

    $("#getCodes").click(function(){
        var phonenum = $("#revertPwdForm input[name='userAccount']").val();
        sendMessage(forgetPwd,phonenum);
    })

});

var count = 60; //注册时所需时间变量
var num = 60;   //找回密码时所需变量
function sendMessage(type,phonenum) {
    var result = isPhoneNum(phonenum);
    if(type=="zc"){  //注册
        if(result=="phone"){  //手机号
            doPostBack("../session/sendShortMsgGetVerificationCode",result,{"phone":phonenum});
            $("#getCode").attr("disabled","true" );//设置按钮为禁用状态
            $("#getCode").val("重新发送(" + count + ")");//更改按钮文字
            SetRegisterTime($("#getCode")); // 启动计时器timer处理函数，1秒执行一次
        }else if(result=="email"){  //邮箱号
            doPostBack("../session/sendMailGetVerificationCode",result,{"email":phonenum});
            $("#getCode").attr("disabled","true" );//设置按钮为禁用状态
            $("#getCode").val("重新发送(" + count + ")");//更改按钮文字
            SetRegisterTime($("#getCode")); // 启动计时器timer处理函数，1秒执行一次
        }else{
            layer.msg("请输入有效的手机号或邮箱");
        }
    }else{ //找回密码
        if(result=="phone"){  //手机号
            doPostBack("../session/sendShortMsgGetVerificationCode",result,{"phone":phonenum});
            // 设置button效果，开始计时
            $("#getCodes").attr("disabled","true" );        //设置按钮为禁用状态
            $("#getCodes").val("重新发送(" + num + ")");  //更改按钮文字
            SetForgetTime($("#getCodes"))       // 启动计时器timer处理函数，1秒执行一次
        }else if(result=="email"){  //邮箱号
            doPostBack("../session/sendMailGetVerificationCode",result,{"email":phonenum});
            // 设置button效果，开始计时
            $("#getCodes").attr("disabled","true" );        //设置按钮为禁用状态
            $("#getCodes").val("重新发送(" + num + ")");  //更改按钮文字
            SetForgetTime($("#getCodes"))       // 启动计时器timer处理函数，1秒执行一次
        }else{
            layer.msg("请输入有效的手机号或邮箱");
        }
    }
}

//timer处理函数
function SetRegisterTime() {
    if (count == 0) {
        $("#getCode").removeAttr("disabled");//移除禁用状态改为可用
        $("#getCode").val("获取验证码");
        count = 60;
        return;
    }else {
        $("#getCode").attr("disabled", true);
        $("#getCode").val("重新发送(" + count + ")");
        count--;
    }
    setTimeout(function() {
            SetRegisterTime($("#getCode")) }
        ,1000)
}

//找回密码时timer处理函数
function SetForgetTime() {
    if (num == 0) {
        $("#getCodes").removeAttr("disabled");//移除禁用状态改为可用
        $("#getCodes").val("获取验证码");
        num = 60;
        return;
    }else {
        $("#getCodes").attr("disabled", true);
        $("#getCodes").val("重新发送(" + num + ")");
        num--;
    }
    setTimeout(function() {
            SetForgetTime($("#getCodes")) }
        ,1000)
}

//将手机利用ajax提交到后台的发短信接口
function doPostBack(url,backFunc,queryParam) {
    $.ajax({
        async : false,
        cache : false,
        type : 'POST',
        url : url,// 请求的action路径
        data:queryParam,
        dataType:'json',
        success : function(data){
            if(data.code==0){
                if(backFunc=="phone"){
                    layer.msg("验证码已发送至手机，请注意查收！");
                }else if(backFunc=="email"){
                    layer.msg("验证码已发送至邮箱，请注意查收！");
                }
            }else{
                layer.msg(data.msg);
            }
        }
    });
}

//校验手机号是否合法
function isPhoneNum(phonenum){
    /*var phonenum = $("#registerForm input[name='userAccount']").val();*/
    var myreg = /^1[34578]\d{9}$/;/*验证手机*/
    var myreg1 = /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;/*验证邮箱*/
    if(myreg.test(phonenum)){
        return "phone";
    }else if(myreg1.test(phonenum)){
        return "email";
    }else{
        return false;
    }
}
/***************结束*******************/

/*注册方法*/
function subRegisterInfo(){
    /*注册表单验证*/
    var $formlist = $('#registerForm');
    var data = $formlist.data('bootstrapValidator');
    if (data) {
        // 修复记忆的组件不验证
        data.validate();
        if (!data.isValid()) {
            return false;
        }
    }
    var formData = {};  //构造参数对象
    formData.name = $("#registerForm input[name='name']").val();
    formData.sex = $("#registerForm input[name='sex']").val();

    var treeObj=$.fn.zTree.getZTreeObj("treeDemo"),
        nodes=treeObj.getCheckedNodes(true),
        organizationId="";//组织机构id
    for(var i=0;i<nodes.length;i++){
        organizationId += nodes[i].id+",";  //获取选中节点的值
    }
    //去掉最后一个逗号
    if (organizationId.length > 0) {
        organizationId = organizationId.substr(0, organizationId.length - 1);
    }
    formData.organizationId = organizationId;
    var userAccount = $("#registerForm input[name='userAccount']").val();
    var myreg = /^1[34578]\d{9}$/;/*验证手机*/
    var myreg1 = /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;/*验证邮箱*/
    if(myreg.test(userAccount)){
        formData.phone = userAccount;
    }else if(myreg1.test(userAccount)){
        formData.email = userAccount;
    }
    formData.verificationCode = $("#registerForm input[name='identifyingCode']").val();
    formData.pwd = $("#registerForm input[name='pwd1']").val();

    /*注册表单提交*/
    $.ajax({
        url:"../session/register",
        data:formData,
        type:"post",
        dataType:"json",
        success:function(data){
            if (data.code==0){
                layer.msg(data.msg);
                $("#registerForm").find(":input").not(":button,#getCode").val("");
                $("#registerForm input[name='sex']").val("");
                $('#registerForm').bootstrapValidator('resetForm');//重置表单是重置表单验证
                swapScreen('login');return false;
            }else{
                layer.msg(data.msg);
            }
        }
    })
}

/*组织机构树结构初始化设置*/
var setting = {
    check: {
        enable: true,
        chkStyle: "radio",
        radioType: "all"
    },
    view: {
        dblClickExpand: false,
        selectedMulti : false
    },
    data: {
        key:{
            checked:"checked",
            children:"children",
            name:"orgName",
            title:"",
            url:""
        },
        simpleData: {
            enable:true,
            idKey: "id",
            pIdKey: "parentId",
            rootPId: ""
        }
    },
    async : {
        enable : true,
        url : "../organ/query",
        dataFilter: filter
    },
    callback: {
        beforeClick: beforeClick,
        onCheck: onCheck
    }
};

function filter(treeId, parentNode, childNodes) {
    if (!childNodes) return null;
    for (var i=0, l=childNodes.length; i<l; i++) {
        childNodes[i].orgName = childNodes[i].orgName.replace(/\.n/g, '.');
    }
    return childNodes;
}

function beforeClick(treeId, treeNode) {
    var zTree = $.fn.zTree.getZTreeObj("treeDemo");
    zTree.checkNode(treeNode, !treeNode.checked, null, true);
    return false;
}

function onCheck(e, treeId, treeNode) {
    var zTree = $.fn.zTree.getZTreeObj("treeDemo"),
        nodes = zTree.getCheckedNodes(true),
        v = "";

    for (var i=0, l=nodes.length; i<l; i++) {
        v += nodes[i].orgName + ",";
        var ids = nodes[i].id;
    }
    if (v.length > 0 ) v = v.substring(0, v.length-1);
    var cityObj = $("#citySel");
    cityObj.attr("value", v);
    $("#organizationId").val(ids).change();
}

function showMenu() {
    var cityObj = $("#citySel");
    var cityOffset = $("#citySel").offset();
    $("#menuContent").css({left:cityOffset.left + "px", top:cityOffset.top + cityObj.outerHeight() + "px"}).slideDown("fast");
    $("body").bind("mousedown", onBodyDown);
    /*$("#citySel").addClass("active");*/
    /*$("#menuBtn").removeClass("fa fa-chevron-down").addClass("fa fa-chevron-up");*/
}
function hideMenu() {
    $("#menuContent").fadeOut("fast");
    $("body").unbind("mousedown", onBodyDown);
    /*$("#menuBtn").removeClass("fa fa-chevron-up").addClass("fa fa-chevron-down");*/
}
function onBodyDown(event) {
    if (!(event.target.id == "menuBtn" || event.target.id == "citySel" || event.target.id == "menuContent" || $(event.target).parents("#menuContent").length>0)) {
        hideMenu();
    }
}